<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户签到管理</span>
      </div>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="签到类型" prop="checkinType">
          <el-select v-model="queryParams.checkinType" placeholder="请选择签到类型" clearable style="width: 200px">
            <el-option label="每日签到" value="1"></el-option>
            <el-option label="旅行地打卡" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打卡时间" prop="checkinDate">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleDailyCheckin" v-hasPermi="['system:user:checkin']">每日签到</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-position" size="mini" @click="handleTravelCheckin" v-hasPermi="['system:user:travelCheckin']">旅行打卡</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="checkinList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="签到类型" align="center" prop="checkinType">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.checkinType === 1">每日签到</el-tag>
            <el-tag v-else-if="scope.row.checkinType === 2">旅行地打卡</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="签到时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地点名称" align="center" prop="locationName" />
        <el-table-column label="详细地址" align="center" prop="address" />
        <el-table-column label="积分" align="center" prop="pointsEarned" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '0'">正常</el-tag>
            <el-tag v-else type="danger">已撤销</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRevoke(scope.row)" v-if="scope.row.status === '0'">撤销</el-button>
            <el-button size="mini" type="text" icon="el-icon-refresh" @click="handleRestore(scope.row)" v-else>恢复</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 每日签到对话框 -->
    <el-dialog :title="dailyCheckinTitle" :visible.sync="dailyCheckinOpen" width="500px" append-to-body>
      <el-form ref="dailyCheckinForm" :model="dailyCheckinForm" :rules="dailyCheckinRules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="dailyCheckinForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDailyCheckinForm">确 定</el-button>
        <el-button @click="cancelDailyCheckin">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 旅行地打卡对话框 -->
    <el-dialog :title="travelCheckinTitle" :visible.sync="travelCheckinOpen" width="600px" append-to-body>
      <el-form ref="travelCheckinForm" :model="travelCheckinForm" :rules="travelCheckinRules" label-width="100px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="travelCheckinForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="地点名称" prop="locationName">
          <el-input v-model="travelCheckinForm.locationName" placeholder="请输入地点名称" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="travelCheckinForm.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="travelCheckinForm.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="travelCheckinForm.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="打卡照片" prop="photos">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            multiple
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="打卡描述" prop="description">
          <el-input v-model="travelCheckinForm.description" type="textarea" placeholder="请输入打卡描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTravelCheckinForm">确 定</el-button>
        <el-button @click="cancelTravelCheckin">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { checkinsList, checkin, travelCheckin } from "@/api/system/checkins";
import { revoke, restore } from "@/api/system/checkins";

export default {
  name: "UserCheckins",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 签到表格数据
      checkinList: [],
      // 弹出层标题
      dailyCheckinTitle: "",
      travelCheckinTitle: "",
      // 是否显示弹出层
      dailyCheckinOpen: false,
      travelCheckinOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        checkinType: null,
        beginTime: null,
        endTime: null
      },
      // 表单参数
      dailyCheckinForm: {},
      travelCheckinForm: {},
      // 文件列表
      fileList: [],
      // 表单校验
      dailyCheckinRules: {
        userId: [{ required: true, message: "用户ID不能为空", trigger: "blur" }]
      },
      travelCheckinRules: {
        userId: [{ required: true, message: "用户ID不能为空", trigger: "blur" }],
        locationName: [{ required: true, message: "地点名称不能为空", trigger: "blur" }],
        latitude: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
        longitude: [{ required: true, message: "经度不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    // 从路由参数中获取userId
    const userId = this.$route.query.userId;
    if (userId && typeof userId !== 'object') {
      this.queryParams.userId = userId;
    }
    this.getList();
  },
  methods: {
    /** 查询签到列表 */
    getList() {
      this.loading = true;
      // 处理日期范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
      
      checkinsList(this.queryParams).then(response => {
        this.checkinList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.queryParams.checkinType = null;
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 每日签到按钮操作 */
    handleDailyCheckin() {
      this.dailyCheckinOpen = true;
      this.dailyCheckinTitle = "每日签到";
      this.dailyCheckinForm = {
        userId: undefined,
        checkinType: 1 // 签到类型：1-每日签到
      };
    },
    /** 旅行打卡按钮操作 */
    handleTravelCheckin() {
      this.travelCheckinOpen = true;
      this.travelCheckinTitle = "旅行地打卡";
      this.travelCheckinForm = {
        userId: undefined,
        checkinType: 2, // 签到类型：2-旅行地打卡
        locationName: undefined,
        latitude: undefined,
        longitude: undefined,
        address: undefined,
        photos: undefined,
        description: undefined
      };
      this.fileList = [];
    },
    /** 文件上传相关方法 */
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
    },
    /** 提交每日签到表单 */
    submitDailyCheckinForm() {
      this.$refs["dailyCheckinForm"].validate(valid => {
        if (valid) {
          // 每日签到只需要传递用户ID和签到类型
          const data = {
            userId: this.dailyCheckinForm.userId,
            checkinType: 1
          };
          checkin(data).then(response => {
            this.$modal.msgSuccess("签到成功");
            this.dailyCheckinOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 提交旅行地打卡表单 */
    submitTravelCheckinForm() {
      this.$refs["travelCheckinForm"].validate(valid => {
        if (valid) {
          // 准备打卡数据
          const travelData = {
            ...this.travelCheckinForm,
            files: this.fileList.map(file => file.raw)
          };
          
          // 直接提交旅行打卡，后端会处理文件上传
          travelCheckin(travelData).then(response => {
            this.$modal.msgSuccess("打卡成功");
            this.travelCheckinOpen = false;
            this.getList();
          }).catch(error => {
            this.$modal.msgError("打卡失败: " + error.message);
          });
        }
      });
    },
    /** 取消每日签到按钮 */
    cancelDailyCheckin() {
      this.dailyCheckinOpen = false;
      this.resetDailyCheckinForm();
    },
    /** 取消旅行打卡按钮 */
    cancelTravelCheckin() {
      this.travelCheckinOpen = false;
      this.resetTravelCheckinForm();
    },
    /** 每日签到表单重置 */
    resetDailyCheckinForm() {
      this.dailyCheckinForm = {
        userId: undefined,
        checkinType: 1
      };
      this.resetForm("dailyCheckinForm");
    },
    /** 旅行打卡表单重置 */
    resetTravelCheckinForm() {
      this.travelCheckinForm = {
        userId: undefined,
        checkinType: 2,
        locationName: undefined,
        latitude: undefined,
        longitude: undefined,
        address: undefined,
        photos: undefined,
        description: undefined
      };
      this.fileList = [];
      this.resetForm("travelCheckinForm");
    },
    /** 撤销签到 */
    handleRevoke(row) {
      this.$modal.confirm('是否确认撤销"' + row.locationName + '"的签到记录？').then(function() {
        return revoke(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤销成功");
      }).catch(() => {});
    },
    /** 恢复签到 */
    handleRestore(row) {
      this.$modal.confirm('是否确认恢复"' + row.locationName + '"的签到记录？').then(function() {
        return restore(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("恢复成功");
      }).catch(() => {});
    }
  }
};
</script>